<template>
  <div
    :style="getBackgroundStyle"
    class="project-form-wrapper"
  >
    <div
      class="progress-wrap"
      v-if="props.formConf?.setting?.enableProgress"
    >
      <el-progress
        :percentage="currentProgress"
        :show-text="false"
      />
    </div>
    <top-login-user v-if="formThemeConfig?.showTopUserInfo" />
    <exam-end-countdown :exam-total-duration="getExamMaxTime" />
    <language-select :form-key="props.formConf?.formKey" />
    <div
      v-if="!showConfirm"
      class="project-form"
    >
      <answer-card
        :field-list="allFields"
        @item-click="handleAnswerCardItemClick"
        v-if="showAnswerCard"
      />
      <div
        class="logo-img-wrap"
        v-if="formThemeConfig?.logoImgUrl"
      >
        <img
          alt="Logo"
          :src="formThemeConfig.logoImgUrl"
          class="logo-img"
        />
      </div>
      <el-image
        v-if="formThemeConfig?.headImgUrl"
        :src="formThemeConfig?.headImgUrl"
        style="width: 100%"
      />
      <div
        class="form-name-text"
        style="text-align: center"
        v-html="formPagesConfig?.title"
      />
      <div
        class="describe-html"
        v-html="formPagesConfig?.description"
      />
      <GenerateForm
        v-if="startParser"
        :key="parserKey"
        :form-conf="formPagesConfig"
        :page-form-model="formData"
        ref="pageContentRef"
        class="p15 mt15"
        @next="nextPage"
        @prev="prevPage"
        @submit="submitForm"
      />
      <div
        class="text-center foot-text"
        v-if="formThemeConfig?.showFootDescription"
      >
        <div v-html="formThemeConfig?.footDescription" />
      </div>
      <p
        class="text-center support-text"
        v-if="formThemeConfig?.showSupport"
      >
        {{ getDevSupport }} {{ $t("rform.gen.powerBy") }}
      </p>
    </div>
    <div
      v-show="showConfirm"
      class="confirm-warp"
    >
      <el-result
        :sub-title="$t('rform.gen.restoreTitle')"
        icon="success"
      >
        <template #icon>
          <img
            src="../../../../assets/images/generateFormIcons/form.png"
            alt=""
          />
        </template>
        <template #extra>
          <div class="flex">
            <el-button
              @click="showConfirm = false"
              size="default"
            >
              {{ $t("rform.gen.noRestore") }}
            </el-button>
            <el-button
              type="primary"
              v-if="showRestoreDataBtnList.includes(1)"
              @click="handleReStore(1)"
              size="default"
            >
              {{ $t("rform.gen.restoreNotSubmit") }}
            </el-button>
            <el-button
              type="primary"
              v-if="showRestoreDataBtnList.includes(2)"
              @click="handleReStore(2)"
              size="default"
            >
              {{ $t("rform.gen.restoreSubmit") }}
            </el-button>
          </div>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts" name="GenerateFormWrap">
import {
  computed,
  defineAsyncComponent,
  inject,
  nextTick,
  onMounted,
  onUnmounted,
  PropType,
  provide,
  Ref,
  ref,
  toValue,
  watch
} from "vue";
import { get, keys, values } from "lodash-es";
import {
  BasicComponent,
  FormConfigType,
  FormThemeType,
  getDefaultFormConfig,
  KeyValueType
} from "@/views/formgen/components/GenerateForm/types/form";
import { deepClone } from "@/views/formgen/utils";
import { setThemeVars } from "@/views/formgen/utils/theme";
import { useFormDataRecovery } from "@/views/formgen/components/GenerateForm/hooks/useFormDataRecovery";
import { storeToRefs } from "pinia";
import { generateId } from "@/utils";
import { getUserName } from "@/utils/auth";
import watermark from "@/utils/watermark";
import GenerateForm from "./GenerateForm.vue";
import { useThemeConfig } from "@/stores/themeConfig";
import { useFormProgress } from "@/views/formgen/components/GenerateForm/hooks/useFormProgress";
import { useExamForm } from "@/views/formgen/components/GenerateForm/hooks/useExamHook";
import {
  FORM_THEME_KEY,
  PREVIEW_MODE_KEY,
  SAVE_FORM_RESTORE_METHOD_KEY,
  USER_FORM_OPTION_LOGIC_STATE_KEY
} from "@/views/formgen/components/GenerateForm/types/constants";
import LanguageSelect from "./component/LanguageSelect.vue";
import { parseLangContent, setFormLangContent } from "../../utils/formI18n";
import { useUserFormInject } from "@/views/formgen/components/GenerateForm/hooks/useUserFormInject";
import { useFormLogic } from "@/views/formgen/components/GenerateForm/hooks/useFormLogicHook";
import { useFormOptionLogic } from "./hooks/useFormOptionLogic";

const ExamEndCountdown = defineAsyncComponent(() => import("./component/ExamEndCountdown.vue"));
const TopLoginUser = defineAsyncComponent(() => import("./component/TopLoginUser.vue"));
const AnswerCard = defineAsyncComponent(() => import("./component/AnswerCard.vue"));

const props = defineProps({
  formConf: {
    type: Object as PropType<FormConfigType>,
    required: true
  },
  // 表单数据
  formData: {
    type: Object,
    default: () => ({})
  },
  // 是否是子表单
  isSubForm: {
    type: Boolean,
    default: false
  }
});

// 开始解析
const startParser = ref<boolean>(false);

// 表单配置详情
const formPagesConfig = ref<FormConfigType>(getDefaultFormConfig());

// 强制表单重新渲染
const parserKey = ref<string>(generateId());

// 主题
const formThemeConfig = inject<Ref<FormThemeType>>(FORM_THEME_KEY);
// 是否是预览
const previewMode = inject<boolean>(PREVIEW_MODE_KEY, false);

// 考试
const { showAnswerCard, getExamMaxTime } = useExamForm();

const themeConfigStore = useThemeConfig();

const { themeConfig } = storeToRefs(themeConfigStore);

// 获取 技术支持文字
const getDevSupport = computed(() => {
  return themeConfig.value.globalTitle ? themeConfig.value.globalTitle : "";
});

// 表单总页数
const getFormPageCount = computed<number>(() => {
  return keys(props.formConf?.perPageFields).length;
});

const userFormStore = useUserFormInject();
const { allFields, currentLang, fieldVisibilityMap } = useUserFormInject();
const { initializeFieldVisibility } = useFormLogic();
const formOptionLogic = useFormOptionLogic();
const { initOptionVisibility } = formOptionLogic;
provide(USER_FORM_OPTION_LOGIC_STATE_KEY, formOptionLogic);

// 数据恢复方法
const { checkRestoreData, saveFormRestoreData, restoreData, showRestoreDataBtnList, showConfirm } = useFormDataRecovery();

provide(SAVE_FORM_RESTORE_METHOD_KEY, saveFormRestoreData);

const pageContentRef = ref<any>(null);

const { currentProgress } = useFormProgress();

onMounted(() => {
  formPagesConfig.value = deepClone(props.formConf);
  // 分页序号存放
  formPagesConfig.value.pageSeqNoObj = {};
  userFormStore.setAllFields(props.formConf?.fields || []);
  // 分页取出每页数据合并 如果字段有分页
  if (keys(formPagesConfig.value.perPageFields)) {
    let allFields: BasicComponent[] = [];
    values(formPagesConfig.value.perPageFields || {}).forEach((value: any) => {
      allFields = allFields.concat(value);
    });
    if (allFields && allFields.length) {
      userFormStore.setAllFields(allFields);
    }
  }
  userFormStore.setCurrentPageConfig(formPagesConfig.value);
  // 初始化字段是否显示隐藏《逻辑》
  initializeFieldVisibility();
  initOptionVisibility();
  startParser.value = true;
  // 检查是否恢复数据
  if (!previewMode) {
    checkRestoreData();
  }
  handleZoomPrevention();
});

onUnmounted(() => {
  watermark.del();
});

watch(
  () => formThemeConfig?.value,
  val => {
    setThemeVars(toValue(val));
    // 设置水印
    if (formThemeConfig?.value?.watermark) {
      let text = formThemeConfig?.value?.watermarkText || "";
      if (formThemeConfig?.value?.watermarkUserName) {
        text = getUserName();
      }
      watermark.del();
      watermark.set(text);
    }
  },
  { immediate: true, deep: true }
);

watch(
  () => currentLang.value,
  val => {
    //更新表单基础信息
    setFormLangContent(formPagesConfig.value, val, props.formConf?.langContent || {});
    // 更新题目
    formPagesConfig.value.fields.forEach((field: any) => {
      parseLangContent(field, val, field?.langContent);
    });
  }
);

// 上一页
const prevPage = (params: any) => {
  if (params.page <= 1) {
    return;
  }
  formPagesConfig.value.pageSeqNoObj[params.page] = params;
  formPagesConfig.value.startSeqNo = formPagesConfig.value.pageSeqNoObj[params.page - 1]?.startSeqNo;
  switchPage(params.page - 1, params);
  // 如果页无有效显示内容 直接跳过
  if (!hasShowField()) {
    params.page = params.page - 1;
    prevPage(params);
  }
};
// 下一页
const nextPage = (params: any) => {
  if (params.page >= getFormPageCount.value) {
    return;
  }
  formPagesConfig.value.pageSeqNoObj[params.page] = params;
  formPagesConfig.value.startSeqNo = params.endSeqNo;
  switchPage(params.page + 1, params);
  // 如果页无有效显示内容 直接跳过
  if (!hasShowField()) {
    params.page = params.page + 1;
    nextPage(params);
    return;
  }
  // 分页滚动到最顶部
  nextTick(() => {
    const container = document.querySelector(".project-form-wrapper");
    if (container) {
      container.scrollTop = 0;
    }
  });
};

const switchPage = (page: number, params: any) => {
  userFormStore.setFormModel(params.formModel);
  formPagesConfig.value.formBtns = keys(formPagesConfig.value.perPageFields).length <= page;
  formPagesConfig.value.fields = get(formPagesConfig.value.perPageFields, page) || [];
  formPagesConfig.value.currentPage = page;
  parserKey.value = generateId();
};

const handleReStore = async (dataType: number) => {
  try {
    await restoreData(parserKey, dataType);
  } catch (error) {
    console.error("Error restoring form data:", error);
  }
};

// 是否有显示字段
const hasShowField = (): boolean => {
  // 过滤掉分页组件本身并检查可见性
  return formPagesConfig.value.fields.some(
    (field: BasicComponent) => field.typeId !== "PAGINATION" && fieldVisibilityMap.value.get(field.vModel)?.isVisible
  );
};

const submitForm = (data: any) => {
  try {
    const setting = props.formConf?.setting;
    if (setting && setting?.saveSubmitStatus) {
      saveFormRestoreData(data.formModel, 2);
    }
  } catch (e) {
    console.error("Error saving form data:", e);
  }
  emit("submit", data);
};

const handleAnswerCardItemClick = (formItemId: string) => {
  pageContentRef.value.scrollToField(formItemId);
};

defineExpose({
  pageContentRef
});

const emit = defineEmits(["submit"]);

// 获取背景的样式
const getBackgroundStyle = computed(() => {
  const style: KeyValueType = {};
  if (formThemeConfig?.value.backgroundColor) {
    style["background"] = formThemeConfig?.value.backgroundColor;
  }
  // 2025-05-15 图片背景在大小不够时候需要放大显示
  if (formThemeConfig?.value.backgroundImg) {
    style["background"] = `url(${formThemeConfig?.value.backgroundImg}) no-repeat center center`;
    style["backgroundSize"] = "cover";
  }
  return style;
});

// 优化缩放处理
const handleZoomPrevention = () => {
  const preventZoom = (event: Event) => {
    if (event instanceof TouchEvent && event.touches.length > 1) {
      event.preventDefault();
    }
  };

  document.addEventListener("touchstart", preventZoom);
  document.addEventListener("gesturestart", preventZoom);
};
// 禁止缩放
//@ts-ignore
document.querySelector("meta[name='viewport']")["content"] =
  "width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no";
</script>

<style lang="scss">
@use "../../assets/styles/elementui-mobile" as *;
@use "../../assets/styles/custom-theme" as *;
</style>
